package it.osg.openstory.dao;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import it.osg.openstory.model.User;


import org.springframework.transaction.annotation.Transactional;


@Transactional
public class JPAUserDAO implements UserDAO {
	private EntityManager entityManager;
	
	@Override
	public User findUser(String mail, String password) throws Exception {
		Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.mail = :mail AND u.password = :password");
		query.setParameter("mail", mail);
		query.setParameter("password", password);
		List<User> users = query.getResultList();
		if (users.isEmpty())
			throw new Exception();
		return users.get(0);
	}
	
	@Override
	public User insertNewUser(User user) {
		entityManager.persist(user);
		entityManager.flush();
		entityManager.close();
		return user;
	}

	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}

	@Override
	public User findUserByName(User user) {
		Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.userName = :username");
		query.setParameter("username", user.getUserName());
		List<User> results = query.getResultList();
		if(results.isEmpty())
			return null;
		else
			return results.get(0);
	}
	
	@Override
	public User findUserByMail(User user) {
		Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.mail = :mail");
		query.setParameter("mail", user.getMail());
		List<User> results = query.getResultList();
		if(results.isEmpty())
			return null;
		else
			return results.get(0);
	}

}
